package cc.spider.web.model.http;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Cookie implements ICookie{
    public static final int DEFAULT_MAX_AGE = -1;

    private final String name;
    private final String value;
    private String path;
    private String domain;
    private Integer maxAge;
    private Date expiry;
    private Boolean secure;
    private Boolean httpOnly;
    private Map<String, String> atts = new HashMap<>();

    public Cookie(String name, String value){
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public String getPath() {
        return path == null? "/": path;
    }

    public void setPath(String path) {
        if(this.path == null){
            this.path = path;
        }
    }

    public String getDomain() {
        return domain;
    }

    public String getDomain(String def){
        return domain == null? def: domain;
    }

    public void setDomain(String domain) {
        if(this.domain == null) {
            this.domain = domain;
        }
    }

    public Integer getMaxAge() {
        return maxAge == null? DEFAULT_MAX_AGE: maxAge;
    }

    public void setMaxAge(Integer maxAge) {
        if (this.maxAge == null) {
            this.maxAge = maxAge;
        }
    }

    public Date getExpiry() {
        return expiry;
    }

    public void setExpiry(Date expiry) {
        if(this.expiry == null) {
            this.expiry = expiry;
        }
    }

    public Boolean getSecure() {
        return secure == null? false: secure;
    }

    public void setSecure(Boolean secure) {
        if(this.secure == null){
            this.secure = secure;
        }
    }

    public Boolean getHttpOnly() {
        return httpOnly == null? false: httpOnly;
    }

    public void setHttpOnly(Boolean httpOnly) {
        if(this.httpOnly == null){
            this.httpOnly = httpOnly;
        }
    }

    public Map<String, String> getAttrs() {
        return new HashMap<>(atts);
    }

    @Override
    public String getAttr(String name, String defaultVal) {
        String val =  this.atts.get(name);
        return val == null? defaultVal: val;
    }

    public void addAttr(String key, String val) {
        if(!this.atts.containsKey(key)){
            this.atts.put(key,val);
        }
    }
}
